import {baseUrl} from '../api/index'
import {appLogin} from './login'

// 检测值类型
const isType = (val, type) => {
  return Object.prototype.toString.call(val).toLowerCase() === '[object ' + type + ']'
}

// 空对象
const isEmptyObject = (obj) => {
  return Object.keys(obj).length === 0 && isType(obj, 'object')
}
const objUrlToParam = (data) => {
  return isEmptyObject(data) ? '' : ('/' + Object.keys(data).map(key => ([key, data[key]].join('/'))).join('/'))
}

// 显示请求错误消息
function showStatusToast (code) {
  let _status = {
    100: '认证通过',
    101: '该帐号已被禁用',
    102: '认证未通过',
    103: '登录凭证过期',
    104: '未获取登录凭证',
  }
  let _title = _status[code]
  if (_title != null) {
    wx.showToast({
      icon: 'none',
      title: _title
    })
  }
}

// 检查是否未登录
function checkIsLogout (token, status) {
  if (!token) {
    return true
  } else {
    return (status === 102 || status === 103 || status === 104)
  }
}

// request
let LoginState = 'logout'
const _Request = (method = 'get', url = '', data = {}, headers = {}) => {
  let _url = url
  let _headers = {}
  let _isLoginUrl = data === 'isLogin'
  let _token = wx.getStorageSync('auth_token')
  // 转换参数类型
  if (method === 'get' && isType(data, 'object')) {
    _url += objUrlToParam(data)
    data = {}
  }
  // 登录接口不需要传递headers token
  if (data === 'isLogin') {
    data = {}
  } else {
    _headers = Object.assign({
      'token': _token,
      'position-x': wx.getStorageSync('user_location_x'),
      'position-y': wx.getStorageSync('user_location_y'),
    }, headers)
  }
  
  return new Promise(function (resolve, reject) {
    // status=101用户被禁用，status=102认证失败，status=103凭证过期
    //发起网络请求
    let __url = baseUrl + _url
    function requestFunc (__url, __method, __data, __headers, __token) {
      wx.request({
        url: __url,
        method: __method,
        data: __data,
        header: __headers,
        success (res) {
          let _status = res.data.status
          let _info = res.data.info
          // 是登录接口请求
          if (_isLoginUrl) {
            if (_status === 1) {
              resolve(res)
            } else {
              reject(res)
            }
          }
  
          // 处理登录出错
          if (_status === 102 || _status === 104) {
            LoginState = 'logout'
          }
          // 需要登录接口请求，检查程序返回结果是否为未登录
          if (checkIsLogout(__token, _status)) {
            if (LoginState === 'logout') {
              wx.hideLoading()
              wx.showLoading({
                title: '登录中...'
              })
              LoginState = 'loading'
              appLogin().then(resLogin => {
                LoginState = 'login'
                wx.hideLoading()
                wx.reLaunch({
                  url: '/pages/index/index'
                })
              }).catch(err => {
                LoginState = 'fail'
              })
              reject(res)
            }
          } else {
            if (_status === 1 || _status === 2 ||
              (isType(_info, 'array') && _info.length > 0) ||
              (isType(_info, 'object') && Object.keys(_info).length > 0)
            ) {
              resolve(res)
            } else {
              reject(res)
            }
          }
        },
        fail (res) {
          reject(res)
        }
      })
    }
    
    requestFunc(__url, method, data, _headers, _token)
  })
}

_Request.get = (url, data, headers) => {
  return _Request('get', url, data, headers)
}
_Request.post = (url, data, headers) => {
  return _Request('post', url, data, headers)
}

export const request = _Request
